package org.ph.share.lock.test.thread2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 执行三个线程顺序输出abcabc
 * Use ReentrantLock and Condition
 *
 * @author Hush.
 * @since 2023/5/18 12:53
 */
@Slf4j
public class Thread18 {
    public static void main(String[] args) throws InterruptedException {

        AwaitAndSignal_1 awaitAndSignal = new AwaitAndSignal_1(2);
        ReentrantLock lock = awaitAndSignal.getLock();
        Condition a = lock.newCondition();
        Condition b = lock.newCondition();
        Condition c = lock.newCondition();
        Thread thread1 = new Thread(() -> awaitAndSignal.print("1", a, b), "t1");
        Thread thread2 = new Thread(() -> awaitAndSignal.print("2", b, c), "t2");
        Thread thread3 = new Thread(() -> awaitAndSignal.print("3", c, a), "t3");
        thread1.start();
        thread2.start();
        thread3.start();

        // 这里存在局限,需要主线程唤醒在a这个Condition中的线程
        // 需要等待以上三个子线程进入await()方法
        Thread.sleep(1000);
        try {
            lock.lock();
            a.signal();
        } finally {
            lock.unlock();
        }

    }
}

@Slf4j
class AwaitAndSignal_1 {


    ReentrantLock lock = new ReentrantLock();

    /**
     * 循环次数
     */
    private final int cycles;

    public AwaitAndSignal_1(int cycles) {
        this.cycles = cycles;
    }

    /**
     * 打印
     *
     * @param currentCondition 当前等待标识
     * @param mess             消息
     * @param nextCondition    下个等待标识
     */
    public void print(String mess, Condition currentCondition, Condition nextCondition) {
        for (int i = 0; i < cycles; i++) {
            lock.lock();
            try {
                // 当前flag不与线程传来的参数一致，进入等待
                try {
                    currentCondition.await();
                    log.info("mess:{}", mess);
                    nextCondition.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            } finally {
                lock.unlock();

            }
        }
    }

    public ReentrantLock getLock() {
        return lock;
    }
}